package com.lagou.util;

import java.util.HashMap;
import java.util.Map;

public class RequestMetrics {

    private static Map<String,MethodCollector> methodTimeMap = new HashMap<>();

    private static Map<String,Metrics> requestMap = new HashMap<>();

    public static void put(String methodName,String requestId){
        requestMap.put(requestId,new Metrics(methodName,System.currentTimeMillis()));
    }

    public static void calculateOnce(String requestId){
        Metrics metrics = requestMap.get(requestId);
        long cost = System.currentTimeMillis() - metrics.getStart();
        MethodCollector collector = methodTimeMap.get(metrics.getMethodName());
        if(collector==null){
            collector = new MethodCollector();
        }
        collector.setTime(metrics.getStart(),cost);
        methodTimeMap.put(metrics.getMethodName(),collector);
        requestMap.remove(requestId);
    }

    public static Map<String,Long> calculate(){
        Map<String,Long> timeMap = new HashMap<>();
        for (String methodName : methodTimeMap.keySet()) {
            MethodCollector collector = methodTimeMap.get(methodName);
            collector.cleanOutTime();
            Map<String,Long> result = collector.getResult();
            result.forEach((key,value)->{
                timeMap.put(methodName+"-"+key,value);
            });
        }
        return timeMap;
    }

}
